package com.utils;

import java.io.PrintStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class JsonUtil
{
  public static Object str2Json(String str)
    throws Exception
  {
    if ((str != null) && (!str.equals(""))) {
      str = str.trim();
      if (str.charAt(0) == '{')
        return JSONObject.fromObject(str);
      if (str.charAt(0) == '[') {
        return JSONArray.fromObject(str);
      }
      return str;
    }

    return "";
  }

  public static String stringify(Object obj)
  {
    if (((obj instanceof List)) || ((obj instanceof String[]))) {
      return JSONArray.fromObject(obj).toString();
    }
    return JSONObject.fromObject(obj).toString();
  }

  public static List<Map<String, Object>> json2List(String jsonStr)
  {
    JSONArray jsonArr = JSONArray.fromObject(jsonStr);

    List list = new ArrayList();
    Iterator it = jsonArr.iterator();
    while (it.hasNext()) {
      Object obj = it.next();
      if ((obj instanceof JSONObject))
        list.add(json2Map(obj.toString()));
      else {
        list.add(obj);
      }
    }

    return list;
  }

  public static Map<String, Object> json2Map(String jsonStr)
  {
    Map map = new HashMap();

    JSONObject json = JSONObject.fromObject(jsonStr);
    for (Iterator localIterator1 = json.keySet().iterator(); localIterator1.hasNext(); ) { Object k = localIterator1.next();
      Object v = json.get(k);

      if ((v instanceof JSONArray))
      {
        List list = new ArrayList();
        Iterator it = ((JSONArray)v).iterator();
        while (it.hasNext()) {
          Object obj = it.next();
          if ((obj instanceof JSONObject))
            list.add(json2Map(obj.toString()));
          else {
            list.add(obj);
          }
        }
        map.put(k.toString(), list);
      } else {
        map.put(k.toString(), v);
      }
    }
    return map;
  }

  public static Object obj2Json(Object obj)
  {
    if ((obj instanceof Map))
      return JSONObject.fromObject(obj);
    if ((obj instanceof List)) {
      return JSONArray.fromObject(obj);
    }
    return null;
  }

  public static void main(String[] args) {
    String str = "{'arr' : ['1', {'b' : 'ee'}, ['3','s','g']]}";
    Map map = json2Map(str);
    System.out.println(map);
  }
}